package com.wsc.it.bridge.push.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.wsc.it.bridge.push.service.PushService;
import com.wsc.it.bridge.push.vo.JieshunLoginResponse;
import com.wsc.it.utils.HttpClientUtil;
import com.wsc.it.utils.RSAUtils;
import com.wsc.it.utils.SignConfig;

@Service
@Component
public class PushServiceImpl implements PushService {
	private static final Logger log = LoggerFactory.getLogger(PushServiceImpl.class);

	@Value("${http.push.jieshun.as}")
	private String jieShunAs;
	@Value("${http.push.jieshun.login}")
	private String jieShunLogin;

	@Override
	public void pushJieShunLogin(HttpServletRequest request, HttpServletResponse response) {
		try {
			String param = HttpClientUtil.parseHttpString(request);
			Map<String, String> paramUrl=	HttpClientUtil.getAllRequestParam(request);
			String url = String.format(this.jieShunLogin, paramUrl.get("cid"),  paramUrl.get("usr"),  paramUrl.get("psw"));
			String responseBody = HttpClientUtil.doPost(url, param);
			log.info("url:{},res={}",url, param, responseBody);
			response.setContentType("application/xml;charset=UTF-8");
			response.getWriter().write(responseBody);
		} catch (IOException e) {
			log.error("", e);
		}

	}
	

	@Override
	public void pushJieShunAs(HttpServletRequest request, HttpServletResponse response) {
		try {
			String param = HttpClientUtil.parseHttpString(request);
			String responseBody = HttpClientUtil.doPost(this.jieShunAs, param);
			log.info("捷顺请求参数：{},res={}", param, responseBody);
			response.setContentType("application/xml;charset=UTF-8");
			response.getWriter().write(responseBody);
		} catch (IOException e) {
			log.error("", e);
		}

	}

	  public String pushJieShunAsTest(HttpServletRequest request, HttpServletResponse response) throws Exception {
	
		  //	下角
		  //String cid = "000000008002125";
	   // String usr = "000000008002125";
	   // String psw = "000000008002125";
	   // String signKey="b483ea5cbccb4da18e576669b396d1dc";
		  
	    String v = "2";
	    //河源
	    String cid = "000000008018203";
	    String usr = "000000008018203";
	    String psw = "000000008018203";
	    String signKey="c8e42e25471c49f5865f85f008726b42";
	    String loginURl = "http://www.jslife.com.cn/jsaims/login?cid=%s&usr=%s&psw=%s";
	    String loginURlFormat = String.format(loginURl, new Object[] { cid, usr, psw });
	    try {
	      DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
	      HttpPost post = new HttpPost(loginURlFormat);
	      HttpResponse httpResponse = defaultHttpClient.execute((HttpUriRequest)post);
	      if (httpResponse.getStatusLine().getStatusCode() == 200) {
	        String loginResponse = EntityUtils.toString(httpResponse.getEntity());
	        log.info("111111  login url:{},res={}", loginURlFormat, loginResponse);
	        JieshunLoginResponse jieshunLoginResponse = (JieshunLoginResponse)JSON.parseObject(loginResponse, JieshunLoginResponse.class);
	        log.info("222222  login {}", JSON.toJSON(jieshunLoginResponse));
	        String url = "http://www.jslife.com.cn/jsaims/as?cid=%s&tn=%s&sn=%s&v=%s&p=%s";
	       
	        String url11 = "http://www.jslife.com.cn/jsaims/as";
	        String p = "{\"serviceId\":\"3c.pay.generateorderbycarno\",\"requestType\":\"DATA\",\"attributes\":{\"carNo\":\"粤-L955DV\"}}";
	        log.info("33333 签名前 json {} ", p);
	        JSONObject object=JSONObject.parseObject(p,Feature.OrderedField);
	        log.info("44444 签名前 JSONObject  {} ", object);
	        String sn=    buildSignJson(object,signKey);
	        log.info("55555 签名后 {} ", sn);
	        String urlFormat = String.format(url,  cid, jieshunLoginResponse.getToken(), sn, v, p );
	       log.info(" 66666 请求  URL:  {}", urlFormat);
	      
	       HttpPost post2 = new HttpPost(urlFormat);
	        /**
	        ArrayList<NameValuePair> list = new ArrayList<>();
	        list.add(new BasicNameValuePair("cid", cid));
	        list.add(new BasicNameValuePair("tn", jieshunLoginResponse.getToken()));
	        list.add(new BasicNameValuePair("sn", sn));
	        list.add(new BasicNameValuePair("v", v));
	        list.add(new BasicNameValuePair("p", p));
	        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list);
	        post2.setEntity(urlEncodedFormEntity);
	        */
	        HttpResponse asResponse = defaultHttpClient.execute(post2);
	        if (asResponse.getStatusLine().getStatusCode() == 200) {
	          log.info("555555  返回信息 url:{},res={}",urlFormat,  asResponse);
	          String asResponseJSON = EntityUtils.toString(asResponse.getEntity());
	          log.info("666666 返回的 URL {} 实体 :{}",urlFormat, asResponseJSON);
	          return asResponseJSON;
	        } 
	        log.info("77777  3c.pay.generateorderbycarno url:{},res={}",  asResponse);
	      } else {
	        log.info("login  error ");
	      } 
	    } catch (Exception e) {
	      log.info(e.getMessage());
	      
	    } 
	    return "";
	  }
	  
	  public static String  buildSignJson(JSONObject jsonObject,String secret) {
	        String sourceStr = buildSourceJSonStr(jsonObject);
	        try {
	            String sign = RSAUtils.sign(sourceStr.getBytes(), secret);
	            return sign;
	        } catch (Exception e) {
	            log.info("加签失败：{} ",e);
	            return null;
	        }
	    }
	    

	  
	    public static String  buildSourceJSonStr(JSONObject param) {
	        // 第一步：参数排序
	        Set<String> keySet = param.keySet();
	        List<String> paramNames = new ArrayList<>(keySet);
	        Collections.sort(paramNames);
	        // 第二步：把所有参数名和参数值串在一起
	        StringBuilder paramNameValue = new StringBuilder();
	        int i = 0;
	        for (String paramName : paramNames) {
	            String val = SignConfig.wrapVal(param.get(paramName));

	            if (i == 0) {
	                paramNameValue.append(paramName).append("=").append(val);
	            } else {
	                paramNameValue.append("&").append(paramName).append("=").append(val);
	            }
	            i++;
	        }

	        String source = paramNameValue.toString();
	        return source;
	    }

	 
}
